package com.aqumon.www.util;

import com.aqumon.www.entity.persistent.JenkinsConfig;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.client.util.EncodingUtils;
import com.offbytwo.jenkins.client.util.UrlUtils;

import java.net.URI;
import java.net.URISyntaxException;

public class JenkinsUtil {

    private static final int DEFAULT_BUFFER_SIZE = 64;

    /**
     * Http 客户端工具
     * 如果有些 API 该Jar工具包未提供，可以用此Http客户端操作远程接口，执行命令
     * @return client
     */
    public static JenkinsHttpClient getClient(JenkinsConfig jenkinsConfig){
        String JENKINS_PASSWORD = jenkinsConfig.getToken() !=null ? jenkinsConfig.getToken(): jenkinsConfig.getPassword();
        JenkinsHttpClient jenkinsHttpClient = null;
        try {
            jenkinsHttpClient = new JenkinsHttpClient(new URI(jenkinsConfig.getJenkinsUrl()), jenkinsConfig.getUserName(), JENKINS_PASSWORD);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return jenkinsHttpClient;
    }

    /**
     * 连接 Jenkins
     */
    public static JenkinsServer connection(JenkinsConfig jenkinsConfig) {
        String JENKINS_PASSWORD = jenkinsConfig.getToken() !=null ? jenkinsConfig.getToken(): jenkinsConfig.getPassword();
        JenkinsServer jenkinsServer = null;
        try {
            jenkinsServer = new JenkinsServer(new URI(jenkinsConfig.getJenkinsUrl()), jenkinsConfig.getUserName(), JENKINS_PASSWORD);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return jenkinsServer;
    }

    public static String toJobBaseUrl(final String jobName) {
        final StringBuilder sb = new StringBuilder(DEFAULT_BUFFER_SIZE);
        sb.append(UrlUtils.toBaseUrl(null));
        if (sb.charAt(sb.length() - 1) != '/') sb.append('/');
        sb.append("job/");
        final String[] jobNameParts = jobName.split("/");

        for (int i = 0; i < jobNameParts.length; i++) {
            sb.append(EncodingUtils.encode(jobNameParts[i]));
            if (i != jobNameParts.length - 1) sb.append('/');
        }
        return sb.toString();
    }

    public static String toFullJobPath(String jobName) {
        String[] parts = jobName.split("/");
        if (parts.length == 1) {
            return parts[0];
        } else {
            StringBuilder sb = new StringBuilder(64);

            for(int i = 0; i < parts.length; ++i) {
                sb.append(parts[i]);
                if (i != parts.length - 1) {
                    sb.append("/job/");
                }
            }
            return sb.toString();
        }
    }
}
